//
//  SettingViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/26.
//

#import "SettingViewController.h"
#import "AboutUsViewController.h"
#import "AccountSetViewController.h"
#import "LoginViewController.h"


@interface SettingViewController ()
@property(nonatomic,strong)UILabel *cacheLabel;
@property(nonatomic,strong)UIButton *clearBtn;
@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
}

-(void)createUI{
    
    [self.customNavigationBar setTitle:@"设置"];
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT+20);
        if(isIPAD){
            make.height.mas_equalTo(@179);
        }else{
            make.height.mas_equalTo(kWFit(179));
        }
    }];
    __weak typeof(self)self_weak_ = self;
    NSArray *arr = @[@"账号设置",@"清理缓存",@"关于我们"];
    for(NSInteger i = 0;i < arr.count;i++){
        UIView *bView = [[UIView alloc]initWithFrame:CGRectMake(0,i*kWFit(63), kScreenWidth-32,kWFit(53))];
        if(isIPAD){
            bView.frame = CGRectMake(0,i*63,self.currentAvailableWidth-32,53);
        }
        bView.tag = 100+i;
        [bgView addSubview:bView];
        if(i == 0||i == 2){
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithActionBlock:^(id  _Nonnull sender) {
                if(i == 2){
                    AboutUsViewController *vc = [[AboutUsViewController alloc]init];
                    [self_weak_.navigationController pushViewController:vc animated:YES];
                }else if (i == 0){
                    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
                    if(userId){
                        AccountSetViewController *vc = [[AccountSetViewController alloc]init];
                        [self_weak_.navigationController pushViewController:vc animated:YES];
                    }else{
                        [self_weak_ login];
                    }
                }
            }];
            [bView addGestureRecognizer:tap];
        }
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.font = JPUIFontPingFangSCMedium(15);
        titleLabel.textColor = KFontBlackColor;
        titleLabel.text = arr[i];
        titleLabel.userInteractionEnabled = YES;
        [bView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@16);
            make.height.mas_equalTo(@21);
            make.centerY.mas_equalTo(bView);
        }];
        if(i == 0||i == 2){
            UIImageView *arrowImageView = [[UIImageView alloc]init];
            arrowImageView.image = [UIImage imageNamed:@"mine_right_arrow"];
            arrowImageView.userInteractionEnabled = YES;
            arrowImageView.tag = 200+i;
            [bView addSubview:arrowImageView];
            [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-12);
                make.width.height.mas_equalTo(@16);
                make.centerY.mas_equalTo(bView);
            }];
        }else if (i == 1){
            UIButton *clearBtn = [[UIButton alloc]init];
            [clearBtn setTitle:@"清理" forState:UIControlStateNormal];
            [clearBtn setTitleColor:KThemeColor forState:UIControlStateNormal];
            clearBtn.titleLabel.font = JPUIFontPingFangSCRegular(14);
            [clearBtn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside];
            [bView addSubview:clearBtn];
            [clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(@-6);
                make.width.mas_equalTo(@48);
                make.height.mas_equalTo(@48);
                make.centerY.mas_equalTo(bView);
            }];
            self.clearBtn = clearBtn;
            self.cacheLabel = [[UILabel alloc]init];
            self.cacheLabel.font = JPUIFontPingFangSCRegular(14);
            self.cacheLabel.textColor = KFontGrayColor;
            self.cacheLabel.textAlignment = NSTextAlignmentRight;
            self.cacheLabel.text = [self calculateCacheSize];
            [bView addSubview:self.cacheLabel];
            [self.cacheLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.mas_equalTo(clearBtn.mas_left).offset(-6);
                make.height.mas_equalTo(@21);
                make.centerY.mas_equalTo(bView);
            }];
            
        }
        
    }
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 获取当前可用宽度并更新布局
        self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
        self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
        self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
        __weak typeof(self)self_weak_ = self;
        for(NSInteger i = 0;i < 3;i++){
            UIView *bView = [self.view viewWithTag:100+i];
            bView.frame = CGRectMake(0,i*63,self.currentAvailableWidth-32,53);
            if(i == 0||i == 2){
                UIImageView *arrowImageView = [bView viewWithTag:200+i];
                [arrowImageView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(@-12);
                    make.centerY.mas_equalTo(bView);
                }];
            }else if (i ==1){
                [self.clearBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(@-6);
                    make.centerY.mas_equalTo(bView);
                }];
                [self.cacheLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.right.mas_equalTo(self_weak_.clearBtn.mas_left).offset(-6);
                    make.centerY.mas_equalTo(bView);
                }];
            }
        }
           
        });
    }
}


#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 清理缓存
-(void)clearBtnClick{
    NSString *cachePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:cachePath error:&error];
    for (NSString *fileName in cacheFiles) {
        NSString *filePath = [cachePath stringByAppendingPathComponent:fileName];
        [fileManager removeItemAtPath:filePath error:nil];
    }
    self.cacheLabel.text = @"0B";
}

#pragma mark - 获取缓存
- (NSString *)formatSize:(unsigned long long)size{
    if (size <= 0) {
        return @"0B";
    }
    NSArray *units = @[@"B", @"KB", @"MB", @"GB", @"TB"];
    NSInteger unitIndex = 0;
    
    while (size >= 1024 && unitIndex < units.count - 1) {
        size /= 1024;
        unitIndex++;
    }
    
    return [NSString stringWithFormat:@"%llu%@", size, units[unitIndex]];
}

- (NSString *)calculateCacheSize{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:cachePath error:&error];
    
    unsigned long long totalSize = 0;
    
    for (NSString *fileName in cacheFiles) {
        NSString *filePath = [cachePath stringByAppendingPathComponent:fileName];
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:nil];
        
        if (fileAttributes) {
            totalSize += [fileAttributes fileSize];
        }
    }
    
    return [self formatSize:totalSize];
}

@end
